#!/bin/bash
echo "================================================"
echo "          交互式 V3.ext 证书生成器"
echo "================================================"

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 获取本机IP
HOST_IP=$(hostname -I | awk '{print $1}')
echo -e "${BLUE}检测到本机IP: $HOST_IP${NC}"
echo ""

# 交互式输入证书目录
echo -e "${YELLOW}请输入证书存放目录（默认: /ssl/certs）:${NC}"
read -r CERT_DIR
if [ -z "$CERT_DIR" ]; then
    CERT_DIR="/ssl/certs"
fi

# 创建证书目录
echo -e "${GREEN}创建目录: $CERT_DIR${NC}"
sudo mkdir -p "$CERT_DIR"
if [ $? -ne 0 ]; then
    echo -e "${RED}错误：无法创建目录 $CERT_DIR${NC}"
    exit 1
fi

# 交互式输入域名
echo ""
echo -e "${YELLOW}请输入要签发的域名（将指向本机IP $HOST_IP）:${NC}"
read -r DOMAIN
if [ -z "$DOMAIN" ]; then
    echo -e "${RED}错误：域名不能为空${NC}"
    exit 1
fi

# 交互式输入有效期
echo ""
echo -e "${YELLOW}请输入证书有效期（天，默认: 365）:${NC}"
read -r DAYS
if [ -z "$DAYS" ]; then
    DAYS=365
fi

# 交互式输入密钥长度
echo ""
echo -e "${YELLOW}请输入密钥长度（默认: 2048）:${NC}"
read -r KEY_SIZE
if [ -z "$KEY_SIZE" ]; then
    KEY_SIZE=2048
fi

echo ""
echo -e "${GREEN}开始生成证书...${NC}"
echo "================================================"

# 生成CA私钥
echo -e "${BLUE}[1/7] 生成CA私钥...${NC}"
sudo openssl genrsa -out "$CERT_DIR/ca.key" "$KEY_SIZE"

# 生成CA证书
echo -e "${BLUE}[2/7] 生成CA证书...${NC}"
sudo openssl req -new -x509 -days "$DAYS" -key "$CERT_DIR/ca.key" -out "$CERT_DIR/ca.crt" \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=MyCompany/CN=My Local CA"

# 生成服务器私钥
echo -e "${BLUE}[3/7] 生成服务器私钥...${NC}"
sudo openssl genrsa -out "$CERT_DIR/server.key" "$KEY_SIZE"

# 生成证书签名请求
echo -e "${BLUE}[4/7] 生成证书签名请求...${NC}"
sudo openssl req -new -key "$CERT_DIR/server.key" -out "$CERT_DIR/server.csr" \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=MyCompany/CN=$DOMAIN"

# 创建V3.ext配置文件
echo -e "${BLUE}[5/7] 创建V3.ext配置文件...${NC}"
sudo tee "$CERT_DIR/v3.ext" > /dev/null << EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = $DOMAIN
DNS.2 = *.$DOMAIN
DNS.3 = localhost
IP.1 = 127.0.0.1
IP.2 = $HOST_IP
EOF

# 使用V3.ext生成证书
echo -e "${BLUE}[6/7] 使用V3.ext生成服务器证书...${NC}"
sudo openssl x509 -req -days "$DAYS" \
  -in "$CERT_DIR/server.csr" \
  -CA "$CERT_DIR/ca.crt" \
  -CAkey "$CERT_DIR/ca.key" \
  -CAcreateserial \
  -out "$CERT_DIR/server.crt" \
  -extfile "$CERT_DIR/v3.ext"

# 清理临时文件
echo -e "${BLUE}[7/7] 清理临时文件...${NC}"
sudo rm -f "$CERT_DIR/server.csr" "$CERT_DIR/ca.srl"

# 设置文件权限
sudo chmod 644 "$CERT_DIR"/*.crt
sudo chmod 600 "$CERT_DIR"/*.key

echo ""
echo "================================================"
echo -e "${GREEN}证书生成完成！${NC}"
echo "================================================"

# 显示生成的证书信息
echo -e "${YELLOW}证书信息:${NC}"
echo "域名: $DOMAIN"
echo "指向IP: $HOST_IP"
echo "有效期: $DAYS 天"
echo "密钥长度: $KEY_SIZE 位"

echo ""
echo -e "${YELLOW}生成的文件:${NC}"
echo "================================================"
sudo ls -la "$CERT_DIR/" | grep -E "\.(crt|key|ext)$"

echo ""
echo -e "${YELLOW}文件详情:${NC}"
echo "----------------------------------------"
for file in "$CERT_DIR"/*.crt "$CERT_DIR"/*.key "$CERT_DIR"/*.ext; do
    if [ -f "$file" ]; then
        filename=$(basename "$file")
        size=$(sudo stat -c%s "$file")
        permissions=$(sudo stat -c%A "$file")
        echo "文件: $filename"
        echo "大小: $size 字节"
        echo "权限: $permissions"
        echo "路径: $file"
        echo "----------------------------------------"
    fi
done

# 验证证书
echo ""
echo -e "${YELLOW}证书验证:${NC}"
sudo openssl x509 -in "$CERT_DIR/server.crt" -text -noout | grep -E "(Subject:|Not Before|Not After |X509v3 Subject Alternative Name)"

# 使用说明
echo ""
echo -e "${YELLOW}使用说明:${NC}"
echo "================================================"
echo "1. 在 /etc/hosts 文件中添加:"
echo "   $HOST_IP    $DOMAIN"
echo ""
echo "2. 配置Web服务器使用证书:"
echo "   SSL证书: $CERT_DIR/server.crt"
echo "   SSL私钥: $CERT_DIR/server.key"
echo ""
echo "3. 客户端需要信任CA证书:"
echo "   CA证书: $CERT_DIR/ca.crt"
echo ""

echo -e "${GREEN}所有证书文件已保存到: $CERT_DIR/${NC}"
